# coding=utf-8
from phosphorusScripts.bedcore.plug.ability import Ability
from phosphorusScripts.bedcore.server import ServerSystem
from phosphorusScripts.modInfo import ModInfo
from phosphorusScripts.server.data import manager


class MainSystem(ServerSystem):

    def __init__(self, namespace, systemName):
        super(MainSystem, self).__init__(namespace, systemName)

    def addEventListen(self, namespace, systemName):
        self.ListenForEvent(namespace, systemName, 'LoadServerAddonScriptsAfter', self, self.LoadServerAddonScriptsAfter)
        self.ListenForEvent(ModInfo.NAME, 'main', 'OpenScreenRequestEvent', self, self.OpenScreenRequestEvent)
        self.ListenForEvent(ModInfo.NAME, 'main', 'OptionChangedEvent', self, self.OptionChangedEvent)
        self.ListenForEvent(ModInfo.NAME, 'main', 'OptionClickedEvent', self, self.OptionClickedEvent)

    def LoadServerAddonScriptsAfter(self, args):
        """
        :type args: dict
        """
        self.BroadcastEvent('PhosphorusLoadedEvent', {})

    def OpenScreenRequestEvent(self, args):
        """
        :type args: dict
        """
        player = args['__id__']
        self.NotifyToClient(player, 'OpenScreenEvent', {
            'isop': Ability.canUseOpCommand(player),
            'server': manager.getScreenData(),
        })

    def OptionChangedEvent(self, args):
        """
        :type args: dict
        """
        player = args['__id__']
        namespace, key = args['namespace'], args['key']
        if not manager.isModifiableOption(namespace, key):
            return
        if manager.getOptionOperator(namespace, key) and not Ability.canUseOpCommand(player):
            return
        value = args['value']
        if not manager.setModifiableOptionCurrent(namespace, key, value):
            return
        data = {
            'namespace': namespace,
            'key': key,
            'value': value,
        }
        callback = manager.getOptionCallback(namespace, key)
        if callable(callback):
            callback(data)
        else:
            self.BroadcastEvent('ServerConfigChangedEvent', data)

    def OptionClickedEvent(self, args):
        """
        :type args: dict
        """
        player = args['__id__']
        namespace, key = args['namespace'], args['key']
        if not manager.isInteractiveOption(namespace, key):
            return
        if manager.getOptionOperator(namespace, key) and not Ability.canUseOpCommand(player):
            return
        data = {
            'namespace': namespace,
            'key': key,
            'playerId': player,
        }
        callback = manager.getOptionCallback(namespace, key)
        if callable(callback):
            callback(data)
        else:
            self.BroadcastEvent('ServerButtonClickedEvent', data)
